
import React, { useEffect, useState } from "react";
import styled from 'styled-components';
import { useNavigate, useLocation } from "react-router-dom";
import { Spin } from 'antd';
import { authGetInforByToken } from '../../services';
import { getToken, setLocalStorage } from '../../utils/index';
import { Window } from '@tauri-apps/api/window';

import { useAuth } from '../../components/auth/auth-provider';
// import { peerStart } from "../../services";

const APPID_1 = "wxd2ed8df26eea65be";

const APPID = "wxdb20e6afea72f948";

const BASE_REDIRECT_URL = "https://www.idns.link/api/wx/login/notify";

export const LoginPage = () => {

    const location = useLocation();

    const navigate = useNavigate();

    const [loading, setLoading] = useState<boolean>(false);

    const [toLogin, setToLogin] = useState<boolean>(false);

    const auth: any = useAuth() // 导入验证上下文属性

    // 获取URL来路，/ or /protected
    let from = location.state?.from?.pathname || '/_settings'

    useEffect(() => {
        if (loading) return;
        setLoading(true);

        const call = async () => {
            let token = getToken();
            if (!token || token == '') {
                setToLogin(true);
                setLoading(false);
                return;
            }
            //判断是否有token，并且token是否有效
            let res: any = await authGetInforByToken(token);
            if (res && res.openid) {
                setLocalStorage("g01_web_openid", res.openid);
                setLocalStorage("g01_unionid", res.unionid);
                setLocalStorage("g01_userid", res.userid);
                console.log(from);
                auth.signin('admin', () => {
                    navigate(from, { replace: true })
                });
            } else {
                //跳转到登录页
                setToLogin(true);
                setLoading(false);
                return;
            }
        };

        call();
    }, []);

    if (loading) {
        return (
            <Container>
                <Spin tip="加载中" size="large">
                    {/* <div className={styles.content} /> */}
                </Spin>
            </Container>
        );
    }

    if (toLogin) {
        //设置window的
        Window.getCurrent().setDecorations(true).then(() => {
            //https://www.idns.link/rrai/web_proxy/index.html#/wx_login_proxy?key=token&token=sasdfasdfasdf
            let redirectUrl = `${BASE_REDIRECT_URL}`;
            let origin = window.location.origin;
            let src = '';
            if (origin.indexOf('http') == 0) {
                //DEBUG
                let localUrl = origin + '/#/tklogin';
                let state = `${encodeURIComponent(localUrl)}`;
                src = `https://open.weixin.qq.com/connect/qrconnect?appid=${APPID}&redirect_uri=${encodeURIComponent(redirectUrl)}&response_type=code&scope=snsapi_login&state=${state}#wechat_redirect`;
            } else {
                src = `https://open.weixin.qq.com/connect/qrconnect?appid=${APPID}&redirect_uri=${encodeURIComponent(redirectUrl)}&response_type=code&scope=snsapi_login&state=`;
            }
            //
            console.log(src);
            window.location.href = src;
        }).catch((err) => {
            console.log(err);
        });
        return (
            <Container>
                <Spin tip="跳转到微信" size="large">
                </Spin>
            </Container>
        );
    } else {
        //
        return (
            <Container>
                <Spin tip="检查是否需要登录" size="large">
                    {/* <div className={styles.content} /> */}
                </Spin>
            </Container>
        );
    }
}


const Container = styled.div`
    display: flex;
    justify-content: center;
    align-items: center;
    background-color: #FFFFFF;
    height: 100%;
    width: 100%;
`;

export default LoginPage;